package com.foreverwin.jzymes.eap.Listener;

import com.foreverwin.jzymes.common.domain.PageData;
import com.foreverwin.jzymes.common.service.IPageDataService;
import com.foreverwin.jzymes.framework.util.ObjectMapperUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Component
public class PageDataListener {

    @Autowired
    IPageDataService pageDataService;

    @JmsListener( destination = "MES_PAGE_DATA" )
    public void receivePageDataFromQueue( String pageDataJson ){
        try {
            PageData pageData = ObjectMapperUtil.readValueForUnderscore( pageDataJson, PageData.class );

            PageData queryParam = new PageData();
            queryParam.setChannel( pageData.getChannel() );
            queryParam.setMsgType( pageData.getMsgType() );
            List<PageData> pageDataList = pageDataService.selectPageDataList( queryParam );
            if( pageDataList.size() == 0 ){
                pageData.setHandle( UUID.randomUUID().toString() );
                pageDataService.insertPageData( pageData );
            }else{
                pageData.setHandle( pageDataList.get( 0 ).getHandle() );
                pageDataService.updatePageData( pageData );
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
